package com.uoko.fileupload.util.example;

import org.junit.Test;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

import static com.uoko.fileupload.util.DeepCopy.deepClone;
import static com.uoko.fileupload.util.FileSave.getRealPath;
import static com.uoko.fileupload.util.FileSave.saveFile;
import static com.uoko.fileupload.util.IsImag.isImag;
import static com.uoko.fileupload.util.SliceUpload.uploaded;

/**
 * <p>
 * 常见文件上传方法
 * </p>
 *
 * @author shaohua
 * Email shaohua@uoko.com
 * created by 2018/6/11
 */
public class CommonFileSeivce {


    /**
     * 大文件上传案例
     */
    @Test
    public void bigFileUpload() {
        String guid = "file.png";
        String md5value = null;
        String chunks = "1";
        String chunk = "1";
        String id = null;
        String name = null;
        String type = null;
        int size = 0;
        MultipartFile file = null;
        String uploadFolderPath = null;
        String fileName;
        try {
            int index;
            String mergePath = uploadFolderPath + guid + "/";
            String ext = name.substring(name.lastIndexOf("."));

            //判断文件是否分块
            index = Integer.parseInt(chunk);
            fileName = String.valueOf(index) + ext;
            // 将文件分块保存到临时文件夹里，便于之后的合并文件
            saveFile(mergePath, fileName, file);
            // 验证所有分块是否上传成功，成功的话进行合并
            uploaded(md5value, guid, chunk, chunks, uploadFolderPath, fileName, ext);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 普通文件上传案例
     */
    @Test
    public void fileUpload() {
        String fileName;
        MultipartFile file = null;
        String name = null;
        try {
            String ext = name.substring(name.lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + ext;
            saveFile(getRealPath(), fileName, file);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    /**
     * 图片上传案例
     */
    @Test
    public void imgUpload() {
        String fileName = "";
        MultipartFile saveFile = null;
        MultipartFile file = null;
        String uploadFolderPath = null;
        String name = null;
        try {
            saveFile = (MultipartFile) deepClone(file);
            java.io.File tempFile = new java.io.File(UUID.randomUUID().toString());
            file.transferTo(tempFile);
            if (!isImag(tempFile)) {
            }
            String realpath = uploadFolderPath;
            String ext = name.substring(name.lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + ext;
            saveFile(realpath, fileName, saveFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
